# !!!此文件为测试文件，实际没有使用
import json
import paho.mqtt.client as mqtt
from thickness_api.settings import mqtt_broker, mqtt_port, username, password

host = mqtt_broker
port = mqtt_port
username = username
password = password

# test/one 回调函数
def one_callback(client, userdata, msg):
    print(msg.topic + ":" + str(msg.payload))
    print("position 1")

def two_callback(client, userdata, msg):
    # payload_dict = eval(msg.payload.decode())
    print(msg.topic + ':' + str(msg.payload))
    print("position 2")

def on_connect(client, userdata, flags, rc):
    msg = '连接失败，位置错误'
    msgs = ['连接成功!', '连接拒绝，协议版本错误', '连接错误，客户端标识符无效', '连接错误，服务器不可用', '连接错误，用户名或密码错误', '连接错误,未授权6-255：当前未使用']
    if rc in range(6):
        msg = msgs[rc]
    print("connect with result code " + str(rc) + ' ' + msg)
    # 订阅消息
    # client.subscribe(topic="test")
    client.subscribe('test/#')
    client.message_callback_add('test/mdata/#', one_callback)
    client.message_callback_add('test/two/mdata', two_callback)
    # 发布消息
    # payload = {
    #     "message": "hello broker 123"
    # }
    # payload = json.dumps(payload)
    # client.publish(topic="test", payload=payload, qos=0, retain=False, properties=None)

# 收到消息时的回调函数
def on_message(client, userdata, msg):
    print(msg.topic + " " + str(msg.payload))
    # 将接收到的消息存储到数据库中
    topic = msg.topic
    payload = msg.payload
    # save_mdata(payload)

client = mqtt.Client(client_id="", clean_session=None, userdata=None, protocol=mqtt.MQTTv311, transport="tcp", reconnect_on_failure=True)
# 需要用户名和密码的情况
client.username_pw_set(username=username, password=password)

client.on_connect = on_connect
client.on_message = on_message

client.connect(host, port, keepalive=60)
client.loop_forever()
